package com.iplant.ams.controller.ams.fxt;

import com.iplant.ams.service.AMSService;
import com.iplant.ams.service.po.ams.asset.AMSAssetInfo;
import com.iplant.ams.service.po.ams.fxt.DMSFrockLedger;
import com.iplant.base.po.ServiceResult;
import com.iplant.base.po.excel.ExcelData;
import com.iplant.base.utils.RetCode;
import com.iplant.base.utils.annotation.trace.TraceAPI;
import com.iplant.base.utils.excel.ExcelReader;
import com.iplant.base.utils.serializer.CloneTool;
import com.iplant.base.utils.general.StringUtils;
import com.iplant.base.utils.sql.orm.ORMUtils;
import com.iplant.base.utils.sql.orm.PoService;
import com.iplant.basic.controller.BasicController;
import com.iplant.basic.service.po.bms.BMSEmployee;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/DMSFrockLedger")
public class DMSFrockLedgerController extends BasicController<DMSFrockLedger> {

    PoService<AMSAssetInfo> AssetInfoService;

    @Autowired
    public AMSService mAMSService;

    public DMSFrockLedgerController() {
        super(DMSFrockLedger.class);
        AssetInfoService = ORMUtils.GetPoService(AMSAssetInfo.class);
    }

    /**
     * 新增或更新
     */
    @TraceAPI(value = "新增或更新")
    @PostMapping("/Update")
    public Object Update(HttpServletRequest request, @RequestBody Map<String, Object> wParam) {
        Object wResult;
        try {
            BMSEmployee wLoginUser = GetSession(request);

            if (!wParam.containsKey("data")) {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
                return wResult;
            }
            DMSFrockLedger wDMSFrockLedger = CloneTool.Clone(wParam.get("data"), DMSFrockLedger.class);

            if (wDMSFrockLedger == null || wDMSFrockLedger.StandardModelID <= 0
                    || wDMSFrockLedger.FrockToolID <= 0) {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
                return wResult;
            }

            ServiceResult<Integer> wServiceResult = mAMSService.DMS_UpdateFrockLedger(wLoginUser, wDMSFrockLedger);

            if (StringUtils.isEmpty(wServiceResult.getFaultCode())) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", null, wDMSFrockLedger);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.getFaultCode());
            }
        } catch (Exception ex) {
            log.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString());
        }
        return wResult;
    }

    /**
     * 新增或更新
     */
    @TraceAPI("批量新增或更新")
    @PostMapping("/UpdateList")
    public Object UpdateList(HttpServletRequest request, @RequestBody Map<String, Object> wParam) {
        Object wResult;
        try {
            BMSEmployee wLoginUser = GetSession(request);

            // ServiceResult<List<AMSAssetStandardModel>> wServiceResult = mPoService.UpdatePoList(wLoginUser, wParam);
            //成功后插入设备型号
            //默认使用设备类型第一个激活的
            if (!wParam.containsKey("data")) {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
                return wResult;
            }
            List<DMSFrockLedger> wList = CloneTool.CloneArray(wParam.get("data"), DMSFrockLedger.class);

            ServiceResult<Integer> wServiceResult = new ServiceResult<>();
            AMSAssetInfo wAMSAssetInfo;
            ServiceResult<AMSAssetInfo> wAssetInfoServiceResult;
            for (DMSFrockLedger wDMSFrockLedger : wList) {

                if (wDMSFrockLedger == null || wDMSFrockLedger.StandardModelID <= 0
                        || wDMSFrockLedger.FrockToolID <= 0) {
                    continue;
                }

                if (wDMSFrockLedger.AssetInfoID > 0) {
                    wAssetInfoServiceResult = AssetInfoService.SelectPO(wLoginUser, wDMSFrockLedger.AssetInfoID, "");
                    wAMSAssetInfo = wAssetInfoServiceResult.Result;
                    if (StringUtils.isNotEmpty(wAssetInfoServiceResult.getFaultCode())) {
                        wServiceResult.FaultCode += wAssetInfoServiceResult.getFaultCode();
                        break;
                    }
                    if (wAMSAssetInfo == null || wAMSAssetInfo.ID <= 0) {
                        wAMSAssetInfo = new AMSAssetInfo(wDMSFrockLedger);
                    } else {
                        wAMSAssetInfo.SetLedger(wDMSFrockLedger);
                    }
                } else {
                    wAMSAssetInfo = new AMSAssetInfo(wDMSFrockLedger);
                }
                wAMSAssetInfo.setUserInfo(wLoginUser);
                wServiceResult = AssetInfoService.UpdatePo(wLoginUser, wAMSAssetInfo);

                if (StringUtils.isNotEmpty(wServiceResult.getFaultCode())) {
                    break;
                }

                wDMSFrockLedger.setUserInfo(wLoginUser);
                wDMSFrockLedger.AssetInfoID = wAMSAssetInfo.ID;

                wDMSFrockLedger.Code = wAMSAssetInfo.Code;
                wServiceResult = mPoService.UpdatePo(wLoginUser, wDMSFrockLedger);
                if (StringUtils.isNotEmpty(wServiceResult.getFaultCode())) {
                    break;
                }
            }
            if (StringUtils.isEmpty(wServiceResult.getFaultCode())) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", wList, null);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.getFaultCode());
            }
        } catch (Exception ex) {
            log.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString());
        }
        return wResult;
    }

    /**
     * 通过编码查询工装台账
     */
    @TraceAPI("通过编码查询")
    @GetMapping("/QueryByCode")
    public Object QueryByCode(HttpServletRequest request) {
        Object wResult = new Object();
        try {
            BMSEmployee wLoginUser = GetSession(request);

            String wCode = StringUtils.parseString(request.getParameter("Code"));

            if (StringUtils.isEmpty(wCode)) {
                return GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
            }

            ServiceResult<DMSFrockLedger> wServiceResult = mAMSService.DMS_QueryFrockLedgerByCode(wLoginUser, wCode);

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", null, wServiceResult.Result);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            log.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString());
        }
        return wResult;
    }

    /**
     * 导入
     */
    @PostMapping("/Import")
    public Object Import(HttpServletRequest request, @RequestParam("file") MultipartFile[] files) {
        Object wResult = new Object();
        try {
            BMSEmployee wLoginUser = GetSession(request);

            if (files.length == 0) {
                return GetResult(RetCode.SERVER_CODE_ERR, "提示：没有要上传的Excel文件！");
            }

            ServiceResult<Integer> wServiceResult = new ServiceResult<>();
            ServiceResult<ExcelData> wExcelData = null;
            String wOriginalFileName = null;
            for (MultipartFile wMultipartFile : files) {
                wOriginalFileName = wMultipartFile.getOriginalFilename();

                assert wOriginalFileName != null;
                if (wOriginalFileName.contains("xlsx"))
                    wExcelData = ExcelReader.getInstance().readMultiSheetExcel(wMultipartFile.getInputStream(),
                            wOriginalFileName, "xlsx", 1000000);
                else if (wOriginalFileName.contains("xls"))
                    wExcelData = ExcelReader.getInstance().readMultiSheetExcel(wMultipartFile.getInputStream(),
                            wOriginalFileName, "xls", 1000000);

                assert wExcelData != null;
                if (StringUtils.isNotEmpty(wExcelData.FaultCode)) {
                    wResult = GetResult(RetCode.SERVER_CODE_ERR, wExcelData.FaultCode);
                    return wResult;
                }

                wServiceResult = mAMSService.DMS_ImportFrockLedger(wLoginUser, wExcelData.Result);

                if (!StringUtils.isEmpty(wServiceResult.FaultCode))
                    break;
            }

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "导入成功!", null, null);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            log.error("Import", ex);
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString());
        }
        return wResult;
    }
}
